const chalk = require('chalk')
const fs = require('fs')
const async = require("async");
const {
  glob,
  globSync,
  globStream,
  globStreamSync,
  Glob,
} = require('glob')

const { isStringAndHasLength, readJSON } = require('../../helper.js')
const ora = require('ora');

/**
 * @description 替换逻辑
 */
async function replaceHandler ({ fileOrDirString, i18nUrl }) {
  let spinner = null;
  try {
    if (typeof fileOrDirString !== 'string' || !isStringAndHasLength(i18nUrl)) {
      console.log('参数有误');
      return
    };
    const fileArr = fileOrDirString.split('&').filter(el => isStringAndHasLength(el))
    if (fileArr.length === 0) {
      return console.log(chalk.red(`参数有误，请检查输入`));
    };
    spinner = ora('替换中').start();

    const i18nArrObject = await readJSON(i18nUrl);
    const i18nArrObjectI18nKey = i18nArrObject.map((el) => el.i18nValue);
    /**
     * 通过value寻找key,替换规则
     */
    function getKeysByValueHandler (value, hasCurlyBraces=true) {
      const filterArr = i18nArrObject.filter((el) => el.i18nValue === value)
      const key = filterArr?.[0].i18nKey;
      return key ? `${hasCurlyBraces ? '{' : ''}intl.get('${key}').d('${value}')${hasCurlyBraces ? '}' : ''}` : value
    }


    const g3 = new Glob('**/src/**', {  ignore: "node_modules/**", withFileTypes: true })
    g3.stream().on('data', async (path) => {
        if (path.isDirectory()) {
            const pathFullpath = path.fullpath()
            const filterMap = path.readdirSync().map(e => e.name).filter(el => el.endsWith('.tsx') || el.endsWith('.jsx') || el.endsWith('.js'));
            
            if (Array.isArray(filterMap) && filterMap.length > 0) {

              for (let i = 0; i < filterMap.length; i++) {
                const nameUrl = filterMap[i];
                const fileUrl= pathFullpath +'\\'+ nameUrl;
                try {
                  const data = await fs.readFileSync(fileUrl, 'utf8');
                  // 匹配前面有等号，前后有单引号或者双引号的连续中文字符 eq: ="操作"
                  const equalSign = /\=(['"])([\u4e00-\u9fa5\，\、\！\，\（\）\：\。\,\!]+)\1/g
          
                  // (?!'\)|"\)|`\))
                  // 匹配前后有单引号或者双引号的连续中文字符
                  const regexHasQuotationMarks = /(['"`])([\u4e00-\u9fa5\，\、\,\！\，\（\）\：\。\!]+(?!'\)|"\)|`\)))\1/g;
        
                  // 匹配连续的中文字符
                  const regex = /(?!\/\/.*|\/\*[\s\S]*?\*\/)[\u4e00-\u9fa5\，\、\,\！\，\（\）\：\。\!]+(?!'\)|"\)|`\))/g;

                  const newdata = data
                  .replace(equalSign, function($1) {
                    // =号 去除前后符号
                    const removeQuotationMarks = $1.slice(2, $1.length-1)
        
                    if (i18nArrObjectI18nKey.includes(removeQuotationMarks)) {
                      return '=' + getKeysByValueHandler(removeQuotationMarks, true)
                    }
                    return $1;
                  })
                  .replace(regexHasQuotationMarks, function($1) {
                    // 去除前后符号
                    const removeQuotationMarks = $1.slice(1, $1.length-1)
        
                    if (i18nArrObjectI18nKey.includes(removeQuotationMarks)) {
                      return getKeysByValueHandler(removeQuotationMarks, false)
                    }
                    return $1;
                  })
                  .replace(regex, function($1) {
                    if (i18nArrObjectI18nKey.includes($1)) {
                      return getKeysByValueHandler($1)
                    }
                    return $1;
                  });


                  await fs.writeFileSync(fileUrl, newdata, "utf8");

                } catch (error) {
                  
                }
                
              }
              console.log(chalk.magenta("文件夹： " + pathFullpath + " 已经替换"));
            } else {
              console.log(chalk.redBright("文件夹： " + pathFullpath + "  -> 没有{.tsx.jsx.js}的文件"));
            }
        }
    })

  } catch (error) {
    console.log("一个错误-3453:", error);
  } finally {
    spinner?.stop?.();
  }
}

module.exports = {
  replaceHandler
}